package com.gthncz.xxhelper;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Build;
import android.provider.Settings;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.gthncz.xxhelper.commons.Params;
import com.gthncz.xxhelper.greendao.ClientDBHelper;
import com.gthncz.xxhelper.service.MainService;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int REQ_OVERLAY_CODE = 0x01;
    private boolean isInitiated = false;
    private ReentrantLock initLock;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initLock = new ReentrantLock();
        // setContentView(R.layout.activity_main);
        initApplication();
        startMainService();
    }

    // 初始化应用数据
    private void initApplication() {
        initLock.lock();
        isInitiated = ClientDBHelper.getInstance(MainActivity.this).isDBInited();
        Log.i(TAG, "Database has intiated ? " + (isInitiated));
        if (isInitiated) {
            initLock.unlock();
            return; // 如果已经初始化了，就不用初始化了
        }

        // 先显示一个进度对话框
        final AppCompatDialog dialog = new AppCompatDialog(this, R.style.AlertDialogNoActionBar);
        LayoutInflater inflater = LayoutInflater.from(this);
        View root = inflater.inflate(R.layout.layout_initing, null);
        dialog.setContentView(root);
        final TextView tv_state = root.findViewById(R.id.textView_initing_state);
        final TextView tv_progress = root.findViewById(R.id.textView_initing_progress);
        final ProgressBar progressBar = root.findViewById(R.id.progressBar_initing);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        // 再注册 BroadcastReceiver
        final BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int flag = intent.getIntExtra("flag", 0x00);
                int size = intent.getIntExtra("size", 0);
                Log.i(TAG, String.format("Receiver flag(%d) size(%d)", flag, size));

                switch(flag){
                    case 0xff:{ // 启动状态
                        tv_state.setText("初始化...");
                        tv_progress.setText(String.format("%d / %d", 0, size));
                        progressBar.setMax(size);
                        progressBar.setProgress(0);
                        break;
                    }
                    case 0xf0:{ // 执行中
                        int index = intent.getIntExtra("index", 0);
                        tv_progress.setText(String.format("%d / %d", index+1, size));
                        progressBar.setMax(size);
                        progressBar.setProgress(index+1);
                        Log.i(TAG, "Receiver index:" + index);
                        break;
                    }
                    case 0x00:{ // 执行完毕
                        tv_state.setText("初始化完成.");
                        // 取消 Receiver 的注册
                        context.unregisterReceiver(this);
                        Log.i(TAG, "初始化完成.");
                        // 延时 2s 对话框消失
                        Timer timer = new Timer() ;
                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        initLock.unlock();
                                        if (dialog.isShowing()){
                                            dialog.dismiss();
                                        }
                                        startMainService();
                                    }
                                });
                            }
                        }, 2000); // 等2s执行
                        break;
                    }
                }
            }
        };
        this.registerReceiver(receiver, new IntentFilter(Params.BROADCAST_INITING));

        // 启动线程, 执行初始化操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                ClientDBHelper.getInstance(MainActivity.this).init();
                isInitiated = ClientDBHelper.getInstance(MainActivity.this).isDBInited();
            }
        }).start();
    }

    // 首页 GO 按钮点击
    public void onGoClicked(View view){
        startMainService();
    }

    private void startMainService() {
        initLock.lock();
        if (isInitiated == false){
            Toast.makeText(this, "没有初始化数据~", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!checkPermissions()){
            requestPermission();
            return;
        }
        Intent intent = new Intent(MainActivity.this, MainService.class);
        Toast.makeText(MainActivity.this, "开始后台运行~", Toast.LENGTH_SHORT).show();
        MainActivity.this.startService(intent);
        finish(); // 关闭自己的activity
    }

    // 检查应用权限
    protected boolean checkPermissions(){
        if (Build.VERSION.SDK_INT >= 23){
            if (Settings.canDrawOverlays(MainActivity.this)){
               // 已经获取到权限
                return true;
            } else {
                // 没有获得权限, 提示获取
                return false;
            }
        } // 低版本的不需要管
        else return true;
    }

    // 请求权限
    private void requestPermission(){
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        Toast.makeText(MainActivity.this, "请授权相应权限~", Toast.LENGTH_SHORT).show();
        MainActivity.this.startActivityForResult(intent, REQ_OVERLAY_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQ_OVERLAY_CODE){
            if (resultCode == Activity.RESULT_OK){
                startMainService(); // 重新尝试
            } else {
                Toast.makeText(MainActivity.this, "应用需要授权才能继续使用！", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

}
